import { PlusOutlined, TagsOutlined, ExportOutlined, ImportOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Spin, Button, Divider, message, Input , Select, Modal, Tag, AutoComplete, Popconfirm, Popover, Badge } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import debounce  from 'lodash.debounce';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import ExportJsonExcel from "js-export-excel";
import AddDevice from './components/AddDevice';
import DeviceRenameDialog from './components/DeviceRenameDialog';
import DeviceOrgEditDialog from './components/DeviceOrgEditDialog';
import DeviceDetail from './components/DeviceDetail';
import DeviceControl from './components/DeviceControl';
import TagCommonComponent from '../System/components/TagCommonComponent';
import ParentOrgListComponent from '../System/components/ParentOrgListComponent';
import GroupListComponent from '../System/components/GroupListComponent';
import AssignTagsModel from '../System/components/AssignTagsModel';
import PlanListComponent from '../System/components/PlanListComponent';
import { DeviceListItem } from './data.d';
import { exportDeviceList, addDevice, removeDevice, renameDevice, changeDeviceOrg, setTag } from './service';
const { Search } = Input;
const { Option } = Select;

const EquipmentList: React.FC<{}> = () => {
  const [spinning, setSpinning] = useState<boolean>(false);
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [detailModalVisible, handleDetailModalVisible] = useState<boolean>(false);
  const [controlModalVisible, handleControlModalVisible] = useState<boolean>(false);
  const [deleteModalVisible, handleDeleteModalVisible] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [renameModalVisible, handleRenameModalVisible] = useState<boolean>(false);
  const [orgModalVisible, handleOrgModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState<DeviceListItem>();
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState<DeviceListItem[]>([]);
  const [tagEnabled, handleTagEnabled] = useState<boolean>(true);
  const [topOrgId, setTopOrgId] = useState<number>(0);
  const [assignTagModalVisible, handleAssignTagModalVisible] = useState<boolean>(false);
  const [disabled, handleDisabled] = useState<boolean>(true);//所属分组是否可用，根据上级机构
  const [total, setTotal] = useState<number>(0);
  const [params, setParams] = useState<DeviceListItem>({});
 
  const tagControl = () =>{
    if(selectedRowKeys.length>0){
      for(let i in selectedRows){
        if(parseInt(i)>0){
          const row1 = selectedRows[parseInt(i)-1];
          const row = selectedRows[i];
          if(row1.topOrgId != row.topOrgId){
            handleTagEnabled(true);
            return;
          }
        }
      }
      setTopOrgId(selectedRows[0].topOrgId);
      handleTagEnabled(false);
    }else{
      handleTagEnabled(true);
    }
  }

  useEffect(() => {
    tagControl();
  },[selectedRowKeys,selectedRows]);
  
  //添加设备
  const addDeviceComment = async (values:DeviceListItem) =>{
    if (values != null && values != undefined) {
      new Promise((resolve, reject) => {
        addDevice(values)
          .then((res) => {
            if (res.code === 200) {
              message.success('添加成功');
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
              resolve(true);
            }else if(res.code == 4501){
              message.error("mac地址已存在");
              resolve(false);
            }else {
              message.error(res.message);
              resolve(false);
            }
          })
          .catch((error) => {
            message.error('请求失败');
            reject(error);
          });
      });
    }
  }
  //编辑设备
  const updateDeviceComment = async (values:DeviceListItem) =>{
    if (values != null && values != undefined) {
        alert("TODO编辑设备")
      // new Promise((resolve, reject) => {
      //   updateDevice(values)
      //     .then((res) => {
      //       if (res.code === 200) {
      //         message.success('添加成功');
      //         handleModalVisible(false);
      //         if (actionRef.current) {
      //           actionRef.current.reload();
      //         }
      //         resolve(true);
      //       }else {
      //         message.error(res.message);
      //         resolve(false);
      //       }
      //     })
      //     .catch((error) => {
      //       message.error('请求失败');
      //       reject(error);
      //     });
      // });
    }
  }

  //添加/编辑弹出框 确定按钮
  const handleUpdate = async (values: DeviceListItem) => {
    if (values != null && values != undefined) {
      let id = values.id;
      if(id){//编辑
        updateDeviceComment(values);
      }else{//添加
        addDeviceComment(values);
      }
    }
  };

  //设备列表--删除弹出框
  const delConfirm = (id: number) => {
    Modal.confirm({
      visible: deleteModalVisible,
      title: '确定删除',
      icon: <QuestionCircleOutlined />,
      content: '此设备将永久删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return new Promise((resolve, reject) => {
          removeDevice(id)
            .then((res) => {
              if (res.code === 200) {
                const hide = message.success('删除成功');
                  handleDeleteModalVisible(false);
                  if (selectedRowKeys.length > 0) {
                    for (var i in selectedRowKeys) {
                      if (selectedRowKeys[i] == id) {
                        selectedRowKeys.splice(parseInt(i), 1);
                      }
                    }
                  }
                  hide();
                  if (selectedRowKeys.length == 0) {
                    setSelectedRowKeys([]);
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest?.();
                  } else {
                    const newRows = selectedRows.concat();
                    for(let i=0;i<selectedRows.length;i++){
                      if(selectedRows[i].id == id){
                        newRows.splice(i, 1);
                      }
                    }
                    setSelectedRows(newRows);
                    actionRef.current?.reload?.();
                  }
                  resolve(true);
              } else {
                message.error('删除失败');
                resolve(false);
              }
            })
            .catch((error) => {
              message.error('删除失败');
              reject(error);
            });
        });
      },
    });
  };

  //分配标签
  const assignTagCommand = (values:any) => {
    const tagsParam = new Object;
    tagsParam["deviceIds"] = selectedRowKeys.toString();
    tagsParam["tagIds"] = values.toString();
    new Promise((resolve, reject) => {
      setTag(tagsParam)
        .then((res) => {
          if (res.code === 200) {
            const hide = message.success('分配成功');
            handleAssignTagModalVisible(false);
            setSelectedRowKeys([]);
            setSelectedRows([]);
            actionRef.current?.reloadAndRest?.();
            hide();
            resolve(true);
          } else {
            message.error('分配失败，' + res.message);
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('删除失败');
          reject(error);
        });
    });
  }

  const onSubmit = (params)=>{
    setParams(params);
  }

  //筛选条件获得数据，不分页
  const getExportList = (params:DeviceListItem) =>{
    setSpinning(true);
    new Promise((resolve, reject) => {
      params.pageSize = 9999;
      params.current = 1;
      exportDeviceList(params)
        .then((res) => {
          if(res && res.code === 200){
            const list = res.data.list;
            for (var i in list) {
              list[i].index = i;
              list[i].key = list[i].id;
              list[i].resolution = list[i].width+'x'+list[i].height;
              if(list[i].registerStatus){
                list[i].registerStatus = "true";
              }else{
                list[i].registerStatus = "false";
              }
            }
            exportDataCommand(list);
            resolve(true);
          }else {
            message.error('请求失败' + res.message);
            resolve(false);
          }
          setSpinning(false);
        })
        .catch((error) => {
          message.error('请求失败');
          reject(error);
        });
    });
  }
  //设备数据导出
  const exportDataCommand = (exportList:Array<DeviceListItem>) =>{
    const exportRows = exportList.map(row=>{
      const item = new Object as DeviceListItem;
      item.name = row.name;
      item.orgName = row.orgName;
      item.groups = row.groups.toString();
      item.mac = row.mac;
      item.resolution = row.resolution;
      item.playStatus = row.playStatus == 'PLAY'?'播放':'空闲';
      item.nowPlanName = row.nowPlanName;
      item.onlineStatus = row.onlineStatus == 'ONLINE'?'在线':'离线';
      item.tags = row.tags.map(tag=>tag.name).toString();
      item.downloadStatus = row.downloadStatus == 'SUCCESS'?'下载成功':row.downloadStatus == 'DOWNLOADING'?'正在下载':row.downloadStatus == 'UNKNOWN'?'未下载':'下载失败';
      return item;
    });
    const sheetColumns = new Array();//导出列构建
    Object.keys(exportRows[0]).map(key => {
      columns.forEach(c =>{
        if(c.dataIndex == key){
          sheetColumns.push(c);
        }
      })
    });
    
    const option = {};
    option.fileName = '设备列表';
    option.datas = [
      {
        
        sheetData: exportRows.map(item => {
            const result = {};
            sheetColumns.forEach(c => {
              result[c.dataIndex] = item[c.dataIndex];
            });
            return result;
        }),
        sheetName: '设备列表',     // Excel文件名称
        sheetFilter: sheetColumns.map(item => item.dataIndex),
        sheetHeader: sheetColumns.map(item => item.title),
        columnWidths: sheetColumns.map(() => 10),
      },
    ];
    const toExcel = new ExportJsonExcel(option);
    toExcel.saveExcel();
  }

  //重置监听
  const onReset = () =>{
    setParams({});
    handleDisabled(true);
  }

  const handleRename = (record:DeviceListItem) =>{
    if (record != null && record != undefined) {
      setLoading(true);
      new Promise((resolve, reject) => {
        renameDevice(record)
          .then((res) => {
            if (res.code === 200) {
              message.success('修改成功');
              handleRenameModalVisible(false);
              actionRef.current?.reload();
              resolve(true);
            }else {
              message.error(res.message);
              resolve(false);
            }
            setLoading(false);
          })
          .catch((error) => {
            message.error('请求失败');
            reject(error);
          });
      });
    }
  }

  const handleOrgEdit = (record:DeviceListItem) =>{
    if (record != null && record != undefined) {
      setLoading(true);
      new Promise((resolve, reject) => {
        changeDeviceOrg(record)
          .then((res) => {
            if (res.code === 200) {
              message.success('修改成功');
              handleOrgModalVisible(false);
              actionRef.current?.reload();
              resolve(true);
            }else {
              message.error(res.message);
              resolve(false);
            }
            setLoading(false);
          })
          .catch((error) => {
            message.error('请求失败');
            reject(error);
          });
      });
    }
  }

  const columns: ProColumns<DeviceListItem>[] = [
    {
      title: '设备名称',
      dataIndex: 'name',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Search
              placeholder="请输入设备名称"
              onSearch={debounce(value=>{form.submit()}, 500)}
              onChange={debounce(value=>{form.submit()}, 500)}
              style={{ width: 200 }}
            />
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
      render: (_,record) => (
        <>
          <Popover placement="right" content={<a onClick={()=>{setFormValues(record);handleRenameModalVisible(true)}}>重命名</a>} title="" trigger="hover">{record.name}</Popover>
        </>
      ),
    },
    {
      title: '所属机构',
      dataIndex: 'orgId',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <ParentOrgListComponent 
              defaultvalue={-1}
              type="orgId"
              selectChange={(value) => {
                form.setFieldsValue({
                  "orgId": value,
                  "groupId":null,
                  "tagIds":null,
                  "nowPlanId":null,
                });
                if(value){
                  handleDisabled(false);
                }else{
                  handleDisabled(true);
                }
                form.submit();
              }}
              >
            </ParentOrgListComponent>
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
    },
    {
      title: '所属机构',
      dataIndex: 'orgName',
      valueType: 'text',
      hideInSearch: true,
      render: (_,record) => (
        <>
          <Popover placement="right" 
          content={
            <a onClick={()=>{setFormValues(record);handleOrgModalVisible(true)}} 
              disabled = {(record.groups.length>0 || record.tags.length>0) ? true:false}>
              {(record.groups.length>0 || record.tags.length>0) ? '请移除设备的标签与分组后再进行所属机构的修改' : '修改'}
            </a>} 
          title="" trigger="hover">{record.orgName}</Popover>
        </>
      ),
    },
    {
      title: '所属分组',
      dataIndex: 'groupId',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        const orgId = form.getFieldValue('orgId');
        let value = "";
        if (status !== 'open') {
          return (
            <GroupListComponent 
              defaultvalue={-1}
              value={value}
              disabled={disabled}
              orgId={orgId>0?orgId:-1}
              selectChange={(value) => {
                form.setFieldsValue({"groupId": value? value:null});
                form.submit();
              }}
            >
          </GroupListComponent>
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
    },
    {
      title: '标签',
      dataIndex: 'tagIds',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        const orgId = form.getFieldValue('orgId');
        let value = "";
        if (status !== 'open') {
          return (
            <TagCommonComponent
              value={value}
              topOrgId = {orgId>0?orgId:JSON.parse(localStorage.getItem("user")).topOrgId}
              selectChange={(values) =>{
                  form.setFieldsValue({"tagIds": values.toString()});
                  form.submit();
                }
              }
            >
            </TagCommonComponent>
          );
        }
        return defaultRender(_);
      },
      hideInTable:true,
      valueType: 'text',
    },
    {
      title: '所属分组',
      dataIndex: 'groups',
      valueType: 'text',
      hideInSearch: true,
      width:150,
      render: groups => (
        <>
          {groups?.map((group, index) => {
            return (
              <Tag color="blue" key={index} title={group} style={{marginBottom:5,display:'inline-block',overflow:'hidden',whiteSpace:'pre',textOverflow:'ellipsis',maxWidth:150}}>
                {group}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: 'MAC地址',
      dataIndex: 'mac',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Search
              placeholder="请输入MAC地址"
              onSearch={debounce(value=>{form.submit()}, 500)}
              onChange={debounce(value=>{form.submit()}, 500)}
              style={{ width: 200 }}
            />
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
    },
    {
      title: '分辨率',
      dataIndex: 'resolution',
      formItemProps:{
        rules:[
          {
            validator: (rule, value, callback) => {
              if(value){
                const n=(value.split('x')).length-1;
                if(n == 1){
                  callback();
                }else{
                  callback("分辨率只能包含一个x，介于长和宽中间");
                }
              }else{
                callback();
              }
            },
          }
        ],
      },  
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <AutoComplete
              style={{ width: 200 }}
              options={[{ label:"全部分辨率",value:''}, { value: '1920x1080' }, { value: '1080x1920' }]}
              onSelect={(value) => {form.submit()}}
            >
              <Input.Search  
                allowClear 
                placeholder="请输入分辨率" 
                onSearch={(value) => {form.submit()}}
              />
            </AutoComplete>
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
    },
    {
      title: '播放状态',
      dataIndex: 'playStatus',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Select
              showSearch
              optionFilterProp="children"
              style={{ width: 200 }}
              placeholder="请选择播放状态"
              onChange={(value) => form.submit()}
            >
              <Option value="">全部</Option>
              <Option value="PLAY">播放</Option>
              <Option value="IDLE">空闲</Option>
            </Select>
          );
        }
        return defaultRender(_);
      },
      valueEnum: {
        PLAY: { text: '播放', status: 'Success' },
        IDLE: { text: '空闲', status: 'Default' },
      },
    },
    {
      title: '当前计划',
      dataIndex: 'nowPlanId',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        const orgId = form.getFieldValue('orgId');
        let value = "";
        if (status !== 'open') {
          return (
            <PlanListComponent
              value={value}
              orgId={orgId>0?orgId:-1}
              disabled={disabled}
              selectChange={(value) => {
                form.setFieldsValue({"nowPlanId": value? value:null});
                form.submit();
              }}
            >

            </PlanListComponent>
          );
        }
        return defaultRender(_);
      },
      hideInTable:true,
      valueType: 'text',
    },
    {
      title: '当前计划',
      dataIndex: 'nowPlanName',
      valueType: 'text',
      hideInSearch: true,
      width:150,
      render:  (_, record) => (
        record.nowPlanName? record.nowPlanName: (
          record.defaultPlanName?<Badge count="默认计划" style={{background:'#1890ff', color:'#fff'}} offset={[30, 0]}><label>{record.defaultPlanName}</label></Badge>:"--")
      )
    },
    {
      title: '在线状态',
      dataIndex: 'onlineStatus',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Select
              showSearch
              optionFilterProp="children"
              style={{ width: 200 }}
              placeholder="请选择"
              onChange={(value) => form.submit()}
            >
              <Option value="">全部</Option>
              <Option value="ONLINE">在线</Option>
              <Option value="OFFLINE">离线</Option>
            </Select>
          );
        }
        return defaultRender(_);
      },
      valueEnum: {
        ONLINE: { text: '在线', status: 'Success' },
        OFFLINE: { text: '离线', status: 'Warning' },
      },
    },
    {
      title: '标签',
      dataIndex: 'tags',
      valueType: 'text',
      width:150,
      hideInSearch: true, 
      render: tags => (
        <>
          {tags?.map((tag, index) => {
            return (
              <Tag color="blue" key={index} title={tag.name} style={{marginBottom:5,display:'inline-block',overflow:'hidden',whiteSpace:'pre',textOverflow:'ellipsis',maxWidth:150}}>
                {tag.name}
              </Tag>
            );
          })}
        </>
      ),
    },
    // {
    //   title: '注册状态',
    //   dataIndex: 'registerStatus',
    //   renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
    //     if (type === 'form') {
    //       return null;
    //     }
    //     const status = form.getFieldValue('state');
    //     if (status !== 'open') {
    //       return (
    //         <Select
    //           showSearch
    //           style={{ width: 200 }}
    //           placeholder="请选择"
    //           onSearch={(value) => form.submit()}
    //           onChange={(value) => form.submit()}
    //         >
    //           <Option value="">全部</Option>
    //           <Option value="true">已注册</Option>
    //           <Option value="false">已添加</Option>
    //         </Select>
    //       );
    //     }
    //     return defaultRender(_);
    //   },
    //   valueEnum: {
    //     "true": { text: '已注册', status: 'Success' },
    //     "false": { text: '未注册', status: 'default' },
    //   },
    // },
    {
      title: '下载状态',
      dataIndex: 'downloadStatus',
      valueType: 'text',
      hideInSearch: true,
      valueEnum: {
        SUCCESS: { text: '下载成功', status: 'Success' },
        DOWNLOADING: { text: '正在下载', status: 'Processing' },
        UNKNOWN: { text: '未下载', status: 'Warning' },
        FAIL: { text: '下载失败', status: 'Error' },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleDetailModalVisible(true);
              setFormValues(record);
            }}
          >
            详情
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              handleControlModalVisible(true);
              setFormValues(record);
            }}
          >
            控制
          </a>
          {/* <Divider type="vertical" />
          <a
            onClick={() => {
              handleModalVisible(true);
              setFormValues(record);
            }}
          >
            编辑
          </a> */}
          <Divider type="vertical" />
          <a 
            onClick={() => {
              delConfirm(record.id);
            }}
          >删除
          </a>
        </>
      ),
    },
  ];

  return (
    <Spin spinning={spinning} tip="导出中请耐心等待..." size="large" style={{marginTop: '20vh',fontSize:16}}>
      <PageContainer>
        <ProTable<DeviceListItem>
          options={false}
          actionRef={actionRef}
          rowKey="key"
          search={{
            labelWidth: 120,
          }}
          pagination={{ showQuickJumper: true,defaultPageSize: 10 }}
          toolBarRender={() => [
            // <Button type="primary" onClick={() => {handleModalVisible(true);setFormValues({});}}>
            //   <PlusOutlined /> 添加设备
            // </Button>,
            // <Button type="primary" onClick={() => console.log("批量添加")}>
            //   <ImportOutlined /> 批量添加
            // </Button>,
            <Button type="primary" 
              disabled={tagEnabled}
              onClick={() => handleAssignTagModalVisible(true)}>
              <TagsOutlined /> 分配标签
            </Button>,
            
            <Popconfirm 
            disabled={total > 0 ? false : true} 
            title={`是否导出${total}条数据？`} onConfirm={() => getExportList(params)}>
              <Button type="primary" 
                disabled={total > 0 ? false : true}
                >
                <ExportOutlined /> 数据导出
              </Button>
            </Popconfirm>,
          ]}
          request={(params, sorter, filter) => exportDeviceList({ ...params, sorter, filter }).then(response=>{
            if (response && response.code === 200) {
              //数据转换
              const obj = new Object();
              let list = response.data.list;
              for (var i in list) {
                list[i].index = i;
                list[i].key = list[i].id;
                list[i].resolution = list[i].width+'x'+list[i].height;
                if(list[i].registerStatus){
                  list[i].registerStatus = "true";
                }else{
                  list[i].registerStatus = "false";
                }
              }
              obj['data'] = response.data.list;
              obj['pageCount'] = response.data.pageCount;
              obj['current'] = response.data.pageNo;
              obj['total'] = response.data.totalCount;
              setTotal(response.data.totalCount);
              return obj;
            }
          })}
          columns={columns}
          onReset={onReset}
          onSubmit={onSubmit}
          onLoad={(data)=>{
            setSelectedRowKeys(selectedRowKeys);
            setSelectedRows(selectedRows);
          }}
          rowSelection={{
            selectedRowKeys:selectedRowKeys,
            onSelect:(record, selected)=>{
              if(selected){//选中
                setSelectedRowKeys([...selectedRowKeys,record.key]);
                setSelectedRows([...selectedRows,record]);
              }else{//取消选中
                const newKeys = selectedRowKeys.concat();
                const index = newKeys.indexOf(record.key);
                newKeys.splice(index, 1);
                setSelectedRowKeys(newKeys);
                
                const newRows = selectedRows.concat();
                for(let i=0;i<selectedRows.length;i++){
                  if(i == index){
                    newRows.splice(index, 1);
                  }
                }
                setSelectedRows(newRows);
              }
            },
            onSelectAll:(selected, selectedRows1, changeRows)=>{
              if(selected){//全选
                const keys = [];
                for(let i=0;i<changeRows.length;i++){
                  const record = changeRows[i];
                  keys.push(record.key);
                }
                setSelectedRowKeys([...selectedRowKeys,...keys]);
                setSelectedRows([...selectedRows,...changeRows]);
              }else{//取消全选
                const newSelectedRowKeys = selectedRowKeys.concat();
                const newSelectedRows = selectedRows.concat();
                for(let i=0;i<changeRows.length;i++){
                  const record = changeRows[i];
                  for(let j=0;j<newSelectedRowKeys.length;j++){
                    if(record.key == newSelectedRowKeys[j]){
                      newSelectedRowKeys.splice(j, 1);
                      newSelectedRows.splice(j, 1);
                    }
                  }
                }
                setSelectedRowKeys(newSelectedRowKeys);
                setSelectedRows(newSelectedRows);
              }
            }
          }}
          tableAlertOptionRender={() => {
            return (<a onClick={() => {
              setSelectedRowKeys([]);
              setSelectedRows([]);
              actionRef.current?.clearSelected?.();
            }}>清空</a>)
          }}
        />
        <AddDevice 
          onSubmit={handleUpdate}
          onCancel={() => handleModalVisible(false)} 
          modalVisible={createModalVisible} 
          values={formValues}
        >
          <ProTable<DeviceListItem, DeviceListItem> />
        </AddDevice>
        <DeviceRenameDialog 
          onSubmit={handleRename}
          loading={loading}
          onCancel={() => handleRenameModalVisible(false)} 
          modalVisible={renameModalVisible} 
          values={formValues}
        >
          <ProTable<DeviceListItem, DeviceListItem> />
        </DeviceRenameDialog>
        <DeviceOrgEditDialog 
          onSubmit={handleOrgEdit}
          loading={loading}
          onCancel={() => handleOrgModalVisible(false)} 
          modalVisible={orgModalVisible} 
          values={formValues}
        >
          <ProTable<DeviceListItem, DeviceListItem> />
        </DeviceOrgEditDialog>
        <AssignTagsModel
          modalVisible={assignTagModalVisible}
          topOrgId={topOrgId}
          onSubmit={assignTagCommand}
          onCancel={()=>handleAssignTagModalVisible(false)}
        >
          <ProTable<DeviceListItem, DeviceListItem> />
        </AssignTagsModel>
        <DeviceDetail 
          onCancel={() => handleDetailModalVisible(false)} 
          modalVisible={detailModalVisible} 
          values={formValues}
        >
          <ProTable<DeviceListItem, DeviceListItem> />
        </DeviceDetail>
        <DeviceControl 
          onCancel={() => handleControlModalVisible(false)} 
          modalVisible={controlModalVisible} 
          values={formValues}
        >
          <ProTable<DeviceListItem, DeviceListItem> />
        </DeviceControl>
      </PageContainer>
    </Spin>
  );
};

export default EquipmentList;
